<script setup lang="ts">
import { ref, reactive, provide } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
import { useLoginAPI, useRegisterAPI } from '@/http/userLogin/index'
import { getTime } from '@/utils/time'
import type { formData } from './type'
import Dialog from '@/views/login/dialog/Dialog.vue'

// Dialog实例
const DialogRef = ref()
const activeName = ref('first')
let router = useRouter()
// let $route = useRoute()
// 登录实例
let loginDataFef = ref()
// 注册实例
let registerDataFef = ref()
let loading = ref<boolean>(false)
// 登录的双向绑定
const loginData: formData = reactive({
  account: '',
  password: '',
})
// 注册的双向绑定
const regData: formData = reactive({
  account: 'admin123',
  password: 'admin123',
  twoPassword: 'admin123',
})
// 请求登录
const onSubmitLogin = async () => {
  try {
    await loginDataFef.value.validate()
    if (loginData.account == '' || loginData.password == '') {
      return ElMessage.error('账号或密码不能为空！')
    }
    const res = await useLoginAPI(loginData)
    const { token } = res
    loading.value = true
    ElMessage({
      type: res.status === 200 ? 'success' : 'error',
      message: res.status === 200 ? '登录成功' : `${res.message}`,
    })
    if (res.status === 200) {
      router.push('/home')
      localStorage.setItem('token', token as string)
      localStorage.setItem('account', loginData.account)
    }
    //判断登录的时候，路由路径是否有query参数，如果有就往query跳，没有就跳转到首页
    // let redirect: any = $route.query.redirect
    // console.log($route.query);
    // $router.push({
    //     path: redirect || '/',
    // })
    ElNotification({
      type: res.status === 200 ? 'success' : 'error',
      message: res.status === 200 ? '登录成功' : `${res.message}`,
      title: res.status === 200 ? `Hi,${getTime()}好` : '',
    })
    loading.value = false
  } catch (error) {
    // 登录失败加载效果消失
    loading.value = false
    ElNotification({
      type: 'error',
      message: (error as Error).message,
    })
  }
}
// 请求注册
const onSubmitRegister = async () => {
  await registerDataFef.value.validate()
  if (
    regData.account == '' ||
    regData.password == '' ||
    regData.twoPassword == ''
  )
    return ElMessage.error('账号或密码不能为空！')
  if (regData.password === regData.twoPassword) {
    const res = await useRegisterAPI(regData)
    ElMessage({
      type: res.status === 200 ? 'success' : 'error',
      message: res.status === 200 ? '注册成功' : `${res.message}`,
    })
    if (res.status === 200) {
      activeName.value = 'first'
    }
  } else {
    ElMessage({
      type: 'error',
      message: '两次输入的密码不一致',
    })
  }
}
// 忘记密码按钮
const onForgetPwd = () => {
  DialogRef.value.forgetPwd.account = ''
  DialogRef.value.forgetPwd.email = ''
  DialogRef.value.goBackDialog = true
}
// 马上注册按钮
const onChangeReg = () => {
  activeName.value = 'second'
}
// 表单验证规则
const rules = reactive({
  account: [
    { required: true, message: '请输入您的账号', trigger: 'blur' },
    { min: 6, max: 12, message: '账号长度在6-12位之间', trigger: 'change' },
  ],
  email: [
    { required: true, message: '请输入您的邮箱', trigger: 'blur' },
    { min: 6, max: 18, message: '邮箱长度在6-18位之间', trigger: 'change' },
  ],
  password: [
    { required: true, message: '请输入您的密码', trigger: 'blur' },
    { min: 6, max: 12, message: '密码长度在6-12位之间', trigger: 'change' },
  ],
  newPassword: [
    { required: true, message: '请输入您的密码', trigger: 'blur' },
    { min: 6, max: 12, message: '密码长度在6-12位之间', trigger: 'change' },
  ],
  twoPassword: [
    { required: true, message: '请再次输入您的密码', trigger: 'blur' },
    { min: 6, max: 12, message: '密码长度在6-12位之间', trigger: 'change' },
  ],
})
provide('rules', rules)
</script>

<template>
  <div class="common-layout">
    <el-container>
      <el-header class="header-wrapped">
        <div class="header-content">
          <h3>通用后台管理系统</h3>
          <span class="welcome">欢迎登录</span>
        </div>
      </el-header>
      <el-main>
        <div class="login-wrapped">
          <el-card>
            <el-tabs v-model="activeName" class="demo-tabs" stretch>
              <el-tab-pane label="登录" name="first">
                <el-form
                  :model="loginData"
                  label-width="auto"
                  style="max-width: 600px"
                  :rules="rules"
                  ref="loginDataFef"
                >
                  <el-form-item label="账号">
                    <el-input
                      v-model="loginData.account"
                      placeholder="请输入账号"
                    />
                  </el-form-item>
                  <el-form-item label="密码">
                    <el-input
                      v-model="loginData.password"
                      type="password"
                      placeholder="请输入密码"
                    />
                  </el-form-item>
                </el-form>
                <div class="footer-wrapped">
                  <span class="forget-password-button" @click="onForgetPwd">
                    忘记密码
                  </span>
                  <el-button
                    type="primary"
                    @click="onSubmitLogin"
                    :loading="loading"
                  >
                    登录
                  </el-button>
                  <div class="noReg-button">
                    <span>还没有账号？</span>
                    <span class="getReg-button" @click="onChangeReg">
                      马上注册
                    </span>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="注册" name="second">
                <el-form
                  :model="regData"
                  label-width="auto"
                  style="max-width: 600px"
                  :rules="rules"
                  ref="registerDataFef"
                >
                  <el-form-item label="账号">
                    <el-input
                      v-model="regData.account"
                      placeholder="账号长度6-12"
                    />
                  </el-form-item>
                  <el-form-item label="密码">
                    <el-input
                      v-model="regData.password"
                      type="password"
                      placeholder="密码长度6-12包含字母和数字"
                    />
                  </el-form-item>
                  <el-form-item label="确认密码">
                    <el-input
                      v-model="regData.twoPassword"
                      type="password"
                      placeholder="再次输入密码"
                    />
                  </el-form-item>
                </el-form>
                <div class="footer-wrapped">
                  <el-button type="primary" @click="onSubmitRegister">
                    注册
                  </el-button>
                </div>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </div>
      </el-main>
      <el-footer class="footer-wrapped">
        <div class="footer-content">
          <div class="title">
            <!-- <span>哈哈哈</span> |
                        <span>哈哈哈</span> |
                        <span>哈哈哈</span> -->
          </div>
        </div>
      </el-footer>
    </el-container>
  </div>
  <Dialog ref="DialogRef"></Dialog>
</template>

<style scoped lang="scss">
.header-wrapped {
  .header-content {
    display: flex;
    width: 1200px;
    margin: 0 auto;
    justify-content: space-between;
    align-items: center;

    .welcome {
      font-size: 13px;
    }
  }
}

.el-main {
  background-image: url('@/assets/background.jpg');

  // height: 600px;
  .login-wrapped {
    width: 1200px;
    margin: 0 auto;
    height: 600px;

    .el-card {
      width: 350px;
      height: 375px;
      float: right;
      position: relative;
      top: 14%;

      .el-form {
        margin-top: 30px;

        .el-input {
          height: 40px;
        }
      }

      .el-button {
        height: 45px;
        width: 100%;
      }

      .footer-wrapped {
        text-align: center;
        font-size: 12px;

        .forget-password-button {
          float: right;
          font-size: 12px;
          color: cornflowerblue;
          margin: 10px;
          cursor: pointer;
        }

        .noReg-button {
          margin: 10px;

          .getReg-button {
            color: cornflowerblue;
            cursor: pointer;
          }
        }
      }
    }
  }
}

.footer-wrapped {
  margin-top: 8px;

  .footer-content {
    display: flex;
    width: 1200px;
    margin: 0 auto;
    justify-content: center;
    align-items: center;

    .title {
      color: #666;
    }

    span {
      color: #666;
      font-size: 12px;
    }
  }
}
</style>
